import axios, { AxiosInterceptorManager } from 'axios'
import type { AxiosInstance } from 'axios'
import type { PXRequestInterceptors, PXRequestConfig } from './type'

import { ElLoading } from 'element-plus/lib'
import { ILoadingInstance } from 'element-plus'

const DEAFULT_LOADING = true

class PXRequest {
  instance: AxiosInstance
  interceptor?: PXRequestInterceptors
  showLoading: boolean
  loading?: ILoadingInstance

  constructor(config: PXRequestConfig) {
    //创建axios实例
    this.instance = axios.create(config)

    //保存基本信息
    this.showLoading = config.showLoading ?? DEAFULT_LOADING
    this.interceptor = config.interceptors

    //使用拦截器
    //1.从config中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptor?.requestInterceptor,
      this.interceptor?.requestnterceptorCatch
    )

    this.instance.interceptors.response.use(
      this.interceptor?.responseInterceptor,
      this.interceptor?.responseInterceptorCatch
    )

    //2.添加所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        console.log('全局拦截：请求成功')

        if (this.showLoading) {
          this.loading = ElLoading.service({
            text: '正在请求数据...',
            lock: true,
            background: 'rgba(0, 0, 0, 0.5)'
          })
        }
        return config
      },
      (error) => {
        console.log('全局拦截：请求失败')
        return error
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        console.log('全局拦截：响应成功')
        this.loading?.close()

        const data = res.data
        return data
        // if (data.returnCode === '-1001') {
        //   console.log('请求失败~，错误信息')
        // } else {
        //   return data
        // }
      },

      (error) => {
        console.log('全局拦截：响应失败')
        this.loading?.close()
        //例子：判断不同的HttpErrorCode显示不同的错误信息
        if (error.response.status === 404) {
          console.log('404的错误~')
        }
        return error
      }
    )
  }

  request<T>(config: PXRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      //1.单个请求对请求config的处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }

      //2.判断是否需要显示loading
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          //1.单个请求对数据的处理
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          //2.将showLoadingZ这种true,这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING

          //3.将结果resolve返回回去
          resolve(res)
        })
        .catch((err) => {
          //将showloading设置true，这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING
          reject(err)
          return err
        })
    })
  }

  get<T>(config: PXRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T>(config: PXRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
  delete<T>(config: PXRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }
  patch<T>(config: PXRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}

export default PXRequest
